﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Areas.Bots.Models;
using Entities;
using Services;

namespace WebUI.Areas.Bots.Controllers
{
    public partial class AdvancedBotTypeController : BaseController
    {
        #region Member Variables

        readonly IBotService _botService;

        #endregion

        #region Constructor

        public AdvancedBotTypeController(ISessionHelper sessionHelper, IBotService botService)
            : base(sessionHelper)
        {
            this._botService = botService;
        }

        #endregion

        public virtual ViewResult Index()
        {
            BotTypeActivity botTypeActivity = BotTypeActivity.ClientMachineIP;

            AdvancedBotTypeViewModel model = new AdvancedBotTypeViewModel
            {
                SelectedBotTypeActivity = Enum.TryParse(_sessionHelper.Bot.BotTypeActivity, out botTypeActivity) ? botTypeActivity : botTypeActivity,
                UnusualTrainingSpan = _sessionHelper.Bot.UnusualTrainingSpan,
                UnusualTrainingValue = _sessionHelper.Bot.UnusualTrainingValue,
                ShowUnusualDataSection = _sessionHelper.Bot.BotType == (short)BotType.UnusualActivity
            };

            return View(model);
        }

        public virtual ActionResult Save(AdvancedBotTypeViewModel model)
        {
            if (ModelState.IsValid)
            {
                _sessionHelper.Bot.BotTypeActivity = model.SelectedBotTypeActivity.ToString();
                _sessionHelper.Bot.UnusualTrainingSpan = model.UnusualTrainingSpan;
                _sessionHelper.Bot.UnusualTrainingValue = model.UnusualTrainingValue;
                model.ShowUnusualDataSection = _sessionHelper.Bot.BotType == (short)BotType.UnusualActivity;//TODO:refactor this part->doubled in Index
                var validationDictionary = _botService.ValidateUnusualActivityData(_sessionHelper.Bot);

                foreach (var error in validationDictionary.Values)
                {
                    ModelState.AddModelError(string.Empty, error);
                }

                if (ModelState.IsValid)
                {
                    return RedirectToRoute(new { action = MVC.Bots.Schedule.ActionNames.Index, controller = MVC.Bots.Schedule.Name, step = MVC.Bots.Schedule.Name });
                }
            }

            return View(MVC.Bots.AdvancedBotType.ActionNames.Index, model);
        }

    }
}